<template>
    <div>
        <div>{{isLogining ? '加载中' : loginResult}}</div>
        <weui-button type="primary" :is_mini="true" v-show="!isLogining" @on-click="on_refresh_click">
            刷新
        </weui-button>
        <div v-for="item in qrcodes">
            <img :src="item.qrcode">
            <div>{{item.username}}</div>
        </div>
    </div>
</template>
<script>
import global from '../lib/global'
import axios from 'axios'
import WeuiButton from '../vue2componentSet/src/components/WeuiButton'

export default {
    components: {
        WeuiButton
    },
    data() {
        return {
            qrcodes: [],
            isLogining: false,
            loginResult: ''
        }
    },
    mounted() {
        this.$store.commit('set_title', '登录淘宝')

        if (!this.$store.state.admin) {
            this.$router.goback()
            return
        }

        this.loginTaobao()
    },
    methods: {
        getTaobaoLoginQrcode() {
            axios.post(global.server + 'getTaobaoLoginQrcode.do', {}).then(result => {
                if (this.isLogining) {
                    const obj = result.data
                    var qrcodes = []
                    obj.qrcodes.forEach(item => {
                        if (item.qrcode)
                            qrcodes.push({
                                qrcode: 'data:image/png;base64,' + item.qrcode,
                                username: item.username
                            })
                    })
                    if (qrcodes.length > 0)
                        this.qrcodes = qrcodes
                    this.getTaobaoLoginQrcode()
                }
            }, result => {
                if (this.isLogining) {
                    this.getTaobaoLoginQrcode()
                }
            })
        },
        loginTaobao() {
            this.isLogining = true
            axios.post(global.server + 'loginTaobao.do', {}).then(result => {
                this.isLogining = false
                const obj = result.data
                if (obj.result == 1) {
                    this.loginResult = obj.successCnt + '个成功，' + obj.failedCnt + '个失败。'
                    obj.failedUsernames.forEach(item => {
                        this.loginResult += item + '失败了，'
                    })
                } else {
                    this.loginResult = '失败'
                }
                this.qrcodes = []
            }, result => {
                this.isLogining = false
                this.loginResult = '访问异常'
                this.qrcodes = []
            })
            this.getTaobaoLoginQrcode()
        },
        on_refresh_click() {
            this.loginTaobao()
        }
    }
}
</script>